package cn.ehanghai.htz.common.utils;

import cn.ehanghai.htz.domain.Position;
import cn.ehanghai.htz.service.PositionService;
import cn.ehanghai.htz.thread.PositionSaveQueueThread;
import dk.tbsalling.aismessages.ais.messages.AISMessage;
import dk.tbsalling.aismessages.ais.messages.Metadata;
import dk.tbsalling.aismessages.ais.messages.PositionReportClassAScheduled;
import dk.tbsalling.aismessages.ais.messages.types.AISMessageType;
import dk.tbsalling.aismessages.nmea.messages.NMEAMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.util.Date;

/**
 * @Author: xumf
 * @Date: 2019/7/4 16:14
 */

public class AisUtil {

    private static final Logger log=LoggerFactory.getLogger(AisUtil.class);


    /**
     * 解析ais报文
     * @param info
     */
    public static void parsingAis(String info){
        if(!StringUtils.isEmpty(info)){
            info= info.trim();
            NMEAMessage nmeaMessage=NMEAMessage.fromString(info);
            int numberOfFragments = nmeaMessage.getNumberOfFragments();
            if(numberOfFragments<=0) {
                log.warn("NMEA message is invalid: ", nmeaMessage.toString());
            }else if(numberOfFragments == 1){
                AISMessage aisMessage;
                aisMessage = AISMessage.create(new Metadata(""), nmeaMessage);
                System.out.println(aisMessage);
//                Instant times=aisMessage.getMetadata().getReceived();
//                Date temp=Date.from(times);
//                System.out.println(DateUtil.dateToString(temp));
                addQueue(aisMessage);
            }

        }
    }

    public static void addQueue(AISMessage aisMessage){
        if(aisMessage.getMessageType() == AISMessageType.PositionReportClassAScheduled){
            PositionReportClassAScheduled msg = (PositionReportClassAScheduled) aisMessage;
            Position p=new Position(msg);
            PositionSaveQueueThread.push(p);
        }

    }

    public static void main(String[] args) {
        String info="!AIVDM,1,1,,A,169>4rh01T8df4fFArF@00000000,0*46";
//        String info1="!AIVDO,1,1,,A,169>10@0008dQOBFBEe000000000,0*41";
//        String info2="!AIVDM,1,1,,A,169>4r@0008dj=@FB32P00000000,0*0E";
//        String info2="!AIVDM,1,1,,A,169>4rP0008diklFAuE000000000,0*35";
//        String info3="!AIVDM,2,1,4,B,55MwW7P00001L@?;GS0<51B08Thj0TdpE800000P0hD556IE07RlSm6P0000,0*0B";
//        parsingAis(info);
//        parsingAis(info1);
        parsingAis(info);
//        parsingAis(info3);
    }
}
